<template>
  <div class="notification-post">
    <h1>发布通知</h1>
    <el-form @submit.prevent="submitNotification">
      <!-- 发布类型下拉框 -->
      <div class="form-group">
        <label for="type">发布类型</label>
        <el-select placeholder="请选择发布类型" v-model="notices.publishertype">
          <el-option
            v-for="item in notification"
            :value="item.id"
            :label="item.type"
            :key="item.id"
          >
            {{ item.type }}
          </el-option>
        </el-select>
      </div>

      <!-- 基地下拉框 -->
      <div class="form-group">
        <label for="base">发布对象</label>
        <el-select id="base" v-model="bases" disabled="true">
          <el-option key="1" value="所有基地" label="所有基地">
            所有基地
          </el-option>
        </el-select>
      </div>

      <!-- 标题 -->
      <div class="form-group">
        <label for="publisher">标题</label>
        <el-input v-model="notices.title"></el-input>
      </div>

      <!-- 内容模板 -->
      <div class="form-group">
        <label for="content">内容</label>
        <div class="editor-box">
          <Toolbar
            style="border-bottom: 1px solid #ccc"
            :editor="editorRef"
            :defaultConfig="toolbarConfig"
            mode="default"
          />
          <Editor
            style="height: 440px; overflow-y: hidden"
            v-model="notices.content"
            :defaultConfig="editorConfig"
            mode="default"
            @onCreated="handleCreated"
          />
        </div>
      </div>
      <el-button type="success" @click="submitNotification">发布</el-button>
    </el-form>
  </div>
</template>

<script setup>
import {
  getCurrentInstance,
  ref,
  onMounted,
  shallowRef,
  reactive,
  onBeforeUnmount,
} from 'vue'
import { ElMessage } from 'element-plus'
import '@wangeditor/editor/dist/css/style.css'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { getAllNoticeType, sendTheNewNotice } from '@/api/publisher'

const { proxy } = getCurrentInstance()
//通知类型对象
let notices = ref({
  publishertype: '',
  title: '',
  notice: '',
  publisher: '',
  createtime: '',
  content: '',
})
//通知类型
const notification = ref([])

//获取所有的通知类型
function getNotificationType() {
  getAllNoticeType().then(res => {
    console.log(res.data)
    notification.value = res.data
  })
}

getNotificationType()
// 假设的基地和用户数据
const bases = ref('所有基地')

function submitNotification() {
  console.log('发布的通知内容:', notices)
  sendTheNewNotice(notices.value).then(res => {
    if (res.code === 200) {
      ElMessage({
        message: '发布成功',
        type: 'success',
      })
    } else {
      ElMessage.error('发布失败！')
    }
    notices.value = {}
  })
}

/**
 * 富文本编辑器
 * @param {Object} editorConfig 编辑器配置
 * @param {String} valueHtml 输入内容
 * @param {Object} toolbarConfig 工具栏配置
 * @param {Function} createEditor 创建编辑器
 * @param {Function} createToolbar 创建工具栏
 * @param {Function} handleChange 编辑器内容变化
 */
const editorRef = shallowRef() // 编辑器实例，必须用 shallowRef
const valueHtml = ref('') // 内容 HTML
// 排除不需要的菜单
const toolbarConfig = {
  excludeKeys: [
    'insertLink',
    'insertImage',
    'editImage',
    'viewImageLink',
    'group-video',
    'emotion',
    'fullScreen',
  ],
}
const editorConfig = { placeholder: '请输入内容...', MENU_CONF: {} }
const handleCreated = editor => {
  editorRef.value = editor // 记录 editor 实例，重要！
}

// 自定义上传
editorConfig.MENU_CONF['uploadImage'] = {
  async customUpload(file, insertFn) {
    let data = new FormData()
    data.append('from', 'article')
    data.append('image', file)
    proxy.$axios
      .post('upload/image', data)
      .then(res => {
        if (res.data.code == 0) {
          let url = proxy.imgUrl + res.data.data.path
          insertFn(url) // 最后插入图片 insertFn(url, alt, href)，alt：描述，href:链接，后面非必填
        } else {
          proxy.$util.messages(res.data.msg, 'error')
        }
      })
      .catch(err => {})
  },
}
// 自定义上传视频
const videoLoading = ref(false)
editorConfig.MENU_CONF['uploadVideo'] = {
  async customUpload(file, insertFn) {
    videoLoading.value = true
    let data = new FormData()
    data.append('file', file)
    proxy.$axios
      .post('upload/video', data)
      .then(res => {
        videoLoading.value = false
        if (res.data.code == 0) {
          let url = proxy.imgUrl + res.data.data.path
          insertFn(url) // 最后插入视频 insertFn(url poster)
        } else {
          proxy.$message({ message: res.data.msg, type: 'error' })
        }
      })
      .catch(err => {
        videoLoading.value = false
      })
  },
}
// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})
</script>

<style scoped>
.notification-post {
  max-width: 900px;
  margin: 0 auto;
  padding: 20px;
  border: 1px solid #7fb942;
  border-radius: 8px;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
}

button {
  padding: 10px 20px;
  background-color: #7fb942;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

button:hover {
  background-color: #429db9;
}
</style>
